{% extends "rbac/base.html" %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-key text-primary"></i> 权限管理</h2>
                <div>
                    <a href="{% url 'rbac:role_list' %}" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left"></i> 返回角色管理
                    </a>
                    <button type="button" class="btn btn-warning" onclick="cleanOrphanedPermissions()">
                        <i class="fas fa-trash-alt"></i> 清理孤立权限
                    </button>
                    <button type="button" class="btn btn-primary" onclick="syncAllPermissions()">
                        <i class="fas fa-sync-alt"></i> 同步所有应用权限
                    </button>
                </div>
            </div>

            {% if messages %}
                {% for message in messages %}
                    <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
                        {{ message }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                {% endfor %}
            {% endif %}
            
            <!-- 搜索和统计信息 -->
            <div class="row mb-4">
                <div class="col-md-8">
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                        </div>
                        <input type="text" class="form-control" id="searchInput" placeholder="搜索权限名称、代码或描述...">
                        <div class="input-group-append">
                            <button class="btn btn-outline-secondary" type="button" onclick="clearSearch()">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="d-flex justify-content-end">
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-outline-info" onclick="expandAll()">
                                <i class="fas fa-expand-arrows-alt"></i> 展开全部
                            </button>
                            <button type="button" class="btn btn-outline-info" onclick="collapseAll()">
                                <i class="fas fa-compress-arrows-alt"></i> 折叠全部
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 统计卡片 -->
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="card border-left-primary shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                        总权限数
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ stats.total_permissions }}</div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-key fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card border-left-success shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                        应用数量
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ stats.total_apps }}</div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-cubes fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card border-left-info shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                        权限分组
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ stats.total_groups }}</div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-layer-group fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card border-left-warning shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                        当前显示
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800" id="visibleCount">{{ stats.total_permissions }}</div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-eye fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 权限列表按应用分组显示 -->
            {% if app_groups %}
                <div class="accordion" id="permissionAccordion">
                    {% for app_name, app_data in app_groups.items %}
                    <div class="card shadow mb-3 app-card" data-app="{{ app_data.app_code }}">
                        <div class="card-header" id="heading{{ forloop.counter }}">
                            <h5 class="mb-0">
                                <button class="btn btn-link btn-block text-left d-flex justify-content-between align-items-center" 
                                        type="button" data-bs-toggle="collapse" 
                                        data-bs-target="#collapse{{ forloop.counter }}" 
                                        aria-expanded="false" 
                                        aria-controls="collapse{{ forloop.counter }}">
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-cubes text-primary me-2"></i>
                                        <strong>{{ app_name }}</strong>
                                        <span class="badge bg-primary ms-2">{{ app_data.total_count }} 个权限</span>
                                    </div>
                                    <i class="fas fa-chevron-down"></i>
                                </button>
                            </h5>
                        </div>
                        
                        <div id="collapse{{ forloop.counter }}" class="collapse" 
                             aria-labelledby="heading{{ forloop.counter }}" 
                             data-bs-parent="#permissionAccordion">
                            <div class="card-body">
                                {% for group_name, perms in app_data.groups.items %}
                                <div class="permission-group mb-4" data-group="{{ group_name }}">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <h6 class="text-info mb-0">
                                            <i class="fas fa-layer-group me-1"></i>
                                            {{ group_name }}
                                            <span class="badge bg-info ms-1">{{ perms|length }}</span>
                                        </h6>
                                    </div>
                                    
                                    <div class="row">
                                        {% for perm in perms %}
                                        <div class="col-md-6 col-lg-4 mb-3">
                                            <div class="card border-left-{{ forloop.parentloop.counter|divisibleby:4|yesno:'success,warning' }} h-100 permission-card" 
                                                 data-permission-name="{{ perm.name|lower }}" 
                                                 data-permission-code="{{ perm.code|lower }}" 
                                                 data-permission-desc="{{ perm.description|lower }}">
                                                <div class="card-body p-3">
                                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                                        <h6 class="card-title text-dark mb-1" title="{{ perm.name }}">
                                                            <i class="fas fa-key text-primary me-1"></i>
                                                            {{ perm.name|truncatechars:20 }}
                                                        </h6>
                                                        <small class="text-muted">{{ perm.created_at|date:"m-d" }}</small>
                                                    </div>
                                                    
                                                    <p class="card-text">
                                                        <small class="text-muted d-block mb-1" title="{{ perm.description }}">
                                                            {{ perm.description|truncatechars:50 }}
                                                        </small>
                                                        <code class="small">{{ perm.code }}</code>
                                                    </p>
                                                    
                                                    <div class="mt-2">
                                                        <span class="badge bg-light border">
                                                            <i class="fas fa-clock me-1"></i>
                                                            {{ perm.created_at|date:"Y-m-d H:i" }}
                                                        </span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        {% endfor %}
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            {% else %}
                <div class="card shadow">
                    <div class="card-body text-center py-5">
                        <i class="fas fa-exclamation-triangle fa-3x text-warning mb-3"></i>
                        <h5>暂无权限数据</h5>
                        <p class="text-muted mb-3">请先同步所有应用权限来创建权限数据</p>
                        <button type="button" class="btn btn-primary" onclick="syncAllPermissions()">
                            <i class="fas fa-sync-alt"></i> 同步所有应用权限
                        </button>
                    </div>
                </div>
            {% endif %}
        </div>
    </div>
</div>

<style>
.border-left-primary {
    border-left: 0.25rem solid #4e73df !important;
}
.border-left-success {
    border-left: 0.25rem solid #1cc88a !important;
}
.border-left-info {
    border-left: 0.25rem solid #36b9cc !important;
}
.border-left-warning {
    border-left: 0.25rem solid #f6c23e !important;
}
.text-gray-300 {
    color: #dddfeb !important;
}
.text-gray-800 {
    color: #5a5c69 !important;
}
.permission-card {
    transition: all 0.3s ease;
    border: 1px solid #e3e6f0;
}
.permission-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
}
.app-card .card-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}
.app-card .btn-link {
    color: white !important;
    text-decoration: none;
}
.app-card .btn-link:hover {
    color: #f8f9fc !important;
}
.app-card .btn-link:focus {
    box-shadow: none;
}
.app-card .btn-link[aria-expanded="true"] .fas.fa-chevron-down {
    transform: rotate(180deg);
}
.app-card .btn-link .fas.fa-chevron-down {
    transition: transform 0.3s ease;
}
.permission-group {
    border-left: 3px solid #e3e6f0;
    padding-left: 15px;
}
.card-title {
    font-size: 0.9rem;
    font-weight: 600;
}
.hidden {
    display: none !important;
}
</style>

<script>
let searchTimeout;

// 搜索功能
function setupSearch() {
    const searchInput = document.getElementById('searchInput');
    searchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            filterPermissions(this.value.toLowerCase());
        }, 300);
    });
}

// 过滤权限
function filterPermissions(searchTerm) {
    const permissionCards = document.querySelectorAll('.permission-card');
    const appCards = document.querySelectorAll('.app-card');
    const groups = document.querySelectorAll('.permission-group');
    let visibleCount = 0;
    
    if (!searchTerm) {
        // 显示所有
        permissionCards.forEach(card => {
            card.classList.remove('hidden');
            visibleCount++;
        });
        groups.forEach(group => group.classList.remove('hidden'));
        appCards.forEach(app => app.classList.remove('hidden'));
    } else {
        // 过滤搜索
        permissionCards.forEach(card => {
            const name = card.getAttribute('data-permission-name') || '';
            const code = card.getAttribute('data-permission-code') || '';
            const desc = card.getAttribute('data-permission-desc') || '';
            
            if (name.includes(searchTerm) || code.includes(searchTerm) || desc.includes(searchTerm)) {
                card.classList.remove('hidden');
                visibleCount++;
            } else {
                card.classList.add('hidden');
            }
        });
        
        // 隐藏空的分组
        groups.forEach(group => {
            const visibleCards = group.querySelectorAll('.permission-card:not(.hidden)');
            if (visibleCards.length === 0) {
                group.classList.add('hidden');
            } else {
                group.classList.remove('hidden');
            }
        });
        
        // 隐藏空的应用
        appCards.forEach(app => {
            const visibleGroups = app.querySelectorAll('.permission-group:not(.hidden)');
            if (visibleGroups.length === 0) {
                app.classList.add('hidden');
            } else {
                app.classList.remove('hidden');
            }
        });
    }
    
    // 更新显示计数
    document.getElementById('visibleCount').textContent = visibleCount;
}

// 清除搜索
function clearSearch() {
    document.getElementById('searchInput').value = '';
    filterPermissions('');
}

// 展开所有
function expandAll() {
    const collapses = document.querySelectorAll('.collapse');
    collapses.forEach(collapse => {
        if (!collapse.classList.contains('show')) {
            new bootstrap.Collapse(collapse, {show: true});
        }
    });
}

// 折叠所有
function collapseAll() {
    const collapses = document.querySelectorAll('.collapse.show');
    collapses.forEach(collapse => {
        new bootstrap.Collapse(collapse, {hide: true});
    });
}

// 同步所有应用权限
function syncAllPermissions() {
    if (!confirm('是否确认同步所有应用的权限？这个操作会扫描所有应用的视图函数并自动生成权限。')) {
        return;
    }
    
    // 显示加载状态
    const button = event.target;
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 同步中...';
    button.disabled = true;
    
    fetch('{% url "rbac:sync_all_permissions" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            clean_orphaned: true  // 自动清理孤立权限
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            let message = '✅ ' + data.message + '\n\n📊 统计信息:\n' +
                  '• 发现视图: ' + data.data.total_discovered + ' 个\n' +
                  '• 新创建权限: ' + data.data.created_count + ' 个\n' +
                  '• 更新权限: ' + data.data.updated_count + ' 个';
            
            if (data.data.deleted_count > 0) {
                message += '\n• 清理孤立权限: ' + data.data.deleted_count + ' 个';
            }
            
            alert(message);
            location.reload();
        } else {
            alert('❌ 同步失败: ' + data.message);
        }
    })
    .catch(error => {
        alert('❌ 网络错误: ' + error);
    })
    .finally(() => {
        // 恢复按钮状态
        button.innerHTML = originalText;
        button.disabled = false;
    });
}

// 清理孤立权限
function cleanOrphanedPermissions() {
    if (!confirm('⚠️ 确认清理孤立权限？\n\n这个操作会删除数据库中对应的视图函数已不存在的权限。\n删除的权限将无法恢复，请谨慎操作！')) {
        return;
    }
    
    // 显示加载状态
    const button = event.target;
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 清理中...';
    button.disabled = true;
    
    fetch('{% url "rbac:clean_orphaned_permissions" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            let message = '✅ ' + data.message;
            
            if (data.data.deleted_count > 0) {
                message += '\n\n🗑️ 已删除的孤立权限:';
                data.data.deleted_permissions.forEach(perm => {
                    message += '\n• ' + perm.name + ' (' + perm.code + ')';
                });
            }
            
            alert(message);
            if (data.data.deleted_count > 0) {
                location.reload(); // 只有删除了权限才刷新页面
            }
        } else {
            alert('❌ 清理失败: ' + data.message);
        }
    })
    .catch(error => {
        alert('❌ 网络错误: ' + error);
    })
    .finally(() => {
        // 恢复按钮状态
        button.innerHTML = originalText;
        button.disabled = false;
    });
}

// 获取CSRF Token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    setupSearch();
    
    // 测试折叠面板功能
    const collapseElements = document.querySelectorAll('.collapse');
    collapseElements.forEach(function(element) {
        element.addEventListener('show.bs.collapse', function() {
            console.log('展开:', element.id);
        });
        element.addEventListener('hide.bs.collapse', function() {
            console.log('收起:', element.id);
        });
    });
    
    console.log('权限列表页面已初始化，发现', collapseElements.length, '个折叠面板');
});
</script>
{% endblock %}